package com.example.multi.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.example.multi.entity.Resp;
import com.example.multi.entity.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/v1/user")
public class UserController {


    @ApiOperation(value = "获取用户列表-id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderCode", value = "订单编号", paramType = "query"),
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Resp<List<Integer>> list(HttpServletRequest request){
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            return Resp.buildFail("接口不存在 404");
        }
        List<Integer> userIds = new ArrayList<>();
        userIds.add(1);

        userIds.add(2);
        userIds.add(3);
        userIds.add(4);
        userIds.add(5);

        handleBusinessTime();

        return Resp.buildDataSuccess(userIds);
    }

    @ApiOperation(value = "根据用户ID获取 用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query"),
    })
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public Resp<User> get(HttpServletRequest request,@RequestParam(value = "userId")Integer userId){
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            return Resp.buildFail("接口不存在 404");
        }
        handleBusinessTime();
        String name = StrUtil.format("用户{}号",userId);
        return Resp.buildDataSuccess(User.builder().id(userId).name(name).build());
    }

    /**
     * 这方法 模拟处理业务或者 去操作数据库 消耗的时间
     */
    public static void handleBusinessTime(){
        //去数据库查询数据耗时 start
        int[] sleepTime = NumberUtil.generateRandomNumber(300,800,1);
        try {
            //Thread.sleep 休眠的时候 相当于 业务操作，或者请求数据库的需要消耗的时间
            Thread.sleep(sleepTime[0]);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //去数据库查询数据耗时 end
    }

}
